﻿using System;
using System.ServiceModel;
using System.Windows;
using System.Windows.Controls;
using Omniscient.Foundation.ApplicationModel;
using Omniscient.Foundation.ApplicationModel.Presentation;
using Omniscient.Foundation.Security;
using Omniscient.TimeTracker.BusinessModel.Security;
using Omniscient.TimeTracker.Presentation;

namespace Omniscient.TimeTracker.Security
{
    /// <summary>
    /// Interaction logic for LoginPrompt.xaml
    /// </summary>
    public partial class LoginPrompt
    {
        public SecurePrincipal Principal { get; set; }

        public LoginPrompt()
        {
            InitializeComponent();
            ButtonOK.IsEnabled = false;
            Principal = null;
            TextBoxUserName.Focus();
        }

        private void ButtonOK_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Retrieve the authenticated principal
                ISecurityService security;
                security = ApplicationManager.Current.ObjectContainer.Get<ISecurityService>();
                Principal = security.GetAuthenticatedUser(TextBoxUserName.Text.Trim(),
                                                          PasswordBoxPassword.Password.Trim());
                Close();
            }
            catch(FaultException<ValidationException> exception)
            {
                ErrorMessage.Content = exception.Reason;

                ExceptionMessage m;
                m = new ExceptionMessage();
                m.Message = exception.Reason.ToString();
                m.ClassName = GetType().Name;
                m.MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;

                IPresenter p = ApplicationManager.Current.PresentationController.GetPresenter<ExceptionPresenter>();
                if(p != null) { p.WriteMessage(m);}
            }
        }

        private void TextBoxUserName_TextChanged(object sender, TextChangedEventArgs e)
        {
            ButtonOK.IsEnabled = !string.IsNullOrEmpty(TextBoxUserName.Text.Trim()) &&
                                 !string.IsNullOrEmpty(PasswordBoxPassword.Password.Trim());
        }

        private void PasswordBoxPassword_PasswordChanged(object sender, RoutedEventArgs e)
        {
            ButtonOK.IsEnabled = !string.IsNullOrEmpty(TextBoxUserName.Text.Trim()) &&
                                 !string.IsNullOrEmpty(PasswordBoxPassword.Password.Trim());
        }

        private void ButtonCancel_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }
    }
}
